<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item prop="ruleCode" label="规则编码：">
            <el-input v-model="filters.ruleCode" placeholder="规则编码"></el-input>
          </el-form-item>
          <el-form-item prop="ruleName" label="规则名称：">
            <el-input v-model="filters.ruleName" placeholder="规则名称"></el-input>
          </el-form-item>
          <el-form-item prop="status" label="状态：">
            <el-select v-model="filters.status" placeholder="状态" style="width:215px">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
          <el-form-item>
            <kt-button label="批量停用" type="active" @click="handleEnable"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <el-row class="t_r">
      <el-button-group>
        <el-tooltip content="刷新" placement="top">
          <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
        </el-tooltip>
        <el-tooltip content="列显示" placement="top">
          <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
        </el-tooltip>
      </el-button-group>
    </el-row>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :highlightCurrentRow="true"
      :content="pageResult"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showSelection="true"
      :showBatchDelete="false"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @selectionChange="selectionChange"
      ref="CyTable"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      title="订单合并规则详情页"
      width="45%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="100px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="id：" prop="id" v-if="false">
            <el-input
              v-model="dataForm.id"
              :disabled="true"
              auto-complete="off"
              placeholder="请输入ID"
            ></el-input>
          </el-form-item>
          <el-form-item label="优先级：" prop="priority">
            <el-input
              v-model="dataForm.priority"
              auto-complete="off"
              type="number"
              placeholder="请输入优先级"
            ></el-input>
          </el-form-item>
          <el-form-item label="规则编码：" prop="ruleCode">
            <el-input
              v-model="dataForm.ruleCode"
              auto-complete="off"
              :disabled="true"
              placeholder="请输入规则编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="规则名称：" prop="ruleName">
            <el-input v-model="dataForm.ruleName" auto-complete="off" placeholder="请输入规则名称"></el-input>
          </el-form-item>
          <el-form-item label="规则状态：" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">可用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效期：" prop="validDate">
            <el-date-picker
              v-model="dataForm.validDate"
              style="width:100%"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input
              v-model="dataForm.remark"
              auto-complete="off"
              type="textarea"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
          <el-form-item label="合单方式：" prop="splitTypeArray">
            <el-checkbox-group v-model="dataForm.splitTypeArray">
              <el-checkbox label="1" name="type">姓名</el-checkbox>
              <el-checkbox label="2" name="type">手机号</el-checkbox>
              <el-checkbox label="3" name="type">地址</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import CyTable from "@/views/Core/ProductTable";
import { param } from "../../../utils";
export default {
  components: {
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      border: true,
      orderSplitConditionEditList: [],
      variableNameOptions: [
        { key: 1, value: "来源渠道" },
        { key: 2, value: "下单来源" },
        { key: 3, value: "商品供应商" }
      ],
      operatorOptions: [],
      conditionValueOptions: [],
      tableData: [],
      size: "small",
      filters: {
        ruleCode: "",
        ruleName: "",
        status: ""
      },
      columns: [
        { prop: "priority", label: "优先级", minWidth: 50 },
        { prop: "ruleCode", label: "规则编码", minWidth: 120 },
        { prop: "ruleName", label: "规则名称", minWidth: 120 },
        {
          prop: "status",
          label: "状态",
          minWidth: 120,
          formatter: this.formateStatus
        }
      ],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: [],
      totalSize: 0,
      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editDialogVisibleMatching: false,
      editLoading: false,
      dataFormRules: {
        priority: [
          { required: true, message: "请输入优先级", trigger: "blur" }
        ],
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "blur" }
        ],
        validDate: [
          { required: true, message: "请输入有效期", trigger: "blur" }
        ],
        splitTypeArray: [
          {
            type: "array",
            required: true,
            message: "请选择合并方式",
            trigger: "change"
          }
        ],
        orderSplitConditionEditList: [
          {
            type: "array",
            required: true,
            message: "请选择匹配条件",
            trigger: "change"
          }
        ]
      },
      // 新增编辑界面数据
      dataForm: {
        id: "",
        priority: "",
        ruleCode: "",
        ruleName: "",
        status: "1",
        startTime: "",
        endTime: "",
        remark: "",
        splitTypeArray: [],
        validDate: "",
        splitType: 0,
        orderSplitConditionEditList: []
      },
      dataFormMatching: {
        conditionValue: [],
        operator: "",
        variableName: ""
      },
      statusList: [],
      checked: []
    };
  },
  methods: {
    // 获取分页数据
    findPage: function(params) {
      let this_ = this;
      if (params == undefined || params == null) {
        params = {
          pageNum: this_.pageRequest.pageNum,
          pageSize: this_.pageRequest.pageSize
        };
      }
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = params.pageNum;
      this_.filters.limit = params.pageSize;
      this.utils.request.queryOrderMerge(this_.filters, function(res) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },
    // 显示新增界面
    //生成规则编码
    setRuleCode: function() {
      let date = new Date();
      let ruleCode = "OS" + date.getTime();
      return ruleCode;
    },
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      this.dataForm.orderSplitConditionEditList = [];
      this.dataForm = {
        priority: "",
        ruleCode: this.setRuleCode(),
        ruleName: "",
        status: 1,
        startTime: "",
        endTime: "",
        remark: "",
        splitType: "",
        splitTypeArray: [],
        validDate: "",
        orderSplitConditionEditList: []
      };
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    //选择框
    selectionChange: function(params) {
      this.checked = params.selections;
    },
    //批量操作
    handleEnable: function() {
      let this_ = this;
      if (this_.checked.length >= 1) {
        let flag = true;
        let ids = "";
        $.each(this_.checked, function(index, val) {
          if (val.status == 2) {
            flag = false;
            this_.$message({ message: "不可停用已停用的数据", type: "error" });
          } else {
            ids += val.id + ",";
          }
        });
        if (flag) {
          let params = {};
          params.ids = ids;
          this.utils.request.editOrderSplitStatus(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "操作成功", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({
                message: "操作失败, " + res.msg,
                type: "error"
              });
            }
          });
        }
      } else {
        this_.$message({ message: "必须选中一条数据", type: "error" });
      }
    },
    // 批量删除
    handleDelete: function(data) {
      var ids = "";
      for (var i = 0; i < data.params.length; i++) {
        ids = ids + data.params[i].id + ",";
      }
      let param = {};
      param.ids = ids;
      this.utils.request.deleteOrderMerge(param, this.deletInfoBack);
    },
    // 批量匹配条件
    handleMatchingDelete: function(rindex, row) {
      var arr = new Array();
      let this_ = this;
      $.each(this_.dataForm.orderSplitConditionEditList, function(index, val) {
        if (rindex == index) {
        } else {
          arr.push(val);
        }
      });
      this_.dataForm.orderSplitConditionEditList = arr;
    },
    // 删除修改回调
    deletInfoBack: function(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
      } else {
        this.$message({ message: "操作失败, " + data.msg, type: "error" });
      }
      this.findPage();
    },
    // 显示编辑界面
    handleEdit: function(params) {
      if (this.$refs["dataForm"] != undefined) {
        this.$refs["dataForm"].clearValidate();
      }
      let this_ = this;
      let array = params.row.splitType.split(",");
      let arraySplitType = new Array();
      $.each(array, function(index, val) {
        if (val != null && val != "") {
          arraySplitType.push(val);
        }
      });
      this_.dataForm = {
          id: params.row.id,
          priority: params.row.priority,
          ruleCode: params.row.ruleCode,
          ruleName: params.row.ruleName,
          status: params.row.status,
          startTime: params.row.startTime,
          endTime: params.row.endTime,
          remark: params.row.remark,
          splitTypeArray: arraySplitType,
          validDate: [params.row.startTime, params.row.endTime]
        };
        this_.editDialogVisible = true;
    },
    // 新增匹配条件
    handleAddMatching: function(row) {
      this.dataFormMatching.operator = "";
      this.dataFormMatching.conditionValue = [];
      this.dataFormMatching.variableName = "";
      this.editDialogVisibleMatching = true;
    },
    // 编辑匹配条件
    handleEditMatching: function(index, row) {
      let this_ = this;
      if (row.variableName == "来源渠道") {
        this_.operatorOptions = [
          { key: 1, value: "=" },
          { key: 2, value: "!=" }
        ];
        this_.conditionValueOptions = [
          { key: "1", value: "BBC" },
          { key: "2", value: "天猫" },
          { key: "3", value: "京东" }
        ];
      } else if (row.variableName == "下单来源") {
        this_.operatorOptions = [{ key: 1, value: "=" }];
        this_.conditionValueOptions = [
          { key: "4", value: "前台下单" },
          { key: "5", value: "后台下单" }
        ];
      } else if (row.variableName == "商品供应商") {
        this_.operatorOptions = [{ key: 3, value: "is not null" }];
        this_.operatorOptions = [{ key: 3, value: "is not null" }];
      }
      this_.dataFormMatching.operator = row.operator;
      this_.dataFormMatching.variableName = row.variableName;
      this_.dataFormMatching.conditionValue = [];
      let conditionValueArray = row.conditionValue.split(",");
      $.each(conditionValueArray, function(index, val) {
        if (val != "" && val != null) {
          this_.dataFormMatching.conditionValue.push(val);
        }
      });
      this.editDialogVisibleMatching = true;
    },
    // 编辑
    submitForm: function() {
      let this_ = this;
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            if (
              this_.dataForm.validDate &&
              this_.dataForm.validDate.length > 0
            ) {
              this_.dataForm.startTime = this_.dataForm.validDate[0];
              this_.dataForm.endTime = this_.dataForm.validDate[1];
            }
            if (
              this_.dataForm.splitTypeArray &&
              this_.dataForm.splitTypeArray.length > 0
            ) {
              let splitType = "";
              $.each(this_.dataForm.splitTypeArray, function(index, val) {
                splitType += val + ",";
              });
              this_.dataForm.splitType = splitType;
            }

            let params = Object.assign({}, this.dataForm);

            this.utils.request.editOrderMerge(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });
                this_.editDialogVisible = false;
                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },

    // 编辑匹配条件
    submitFormMatching: function() {
      let this_ = this;
      if (this_.dataFormMatching.conditionValue.length == 0) {
        this.$message({ message: "请选择匹配条件", type: "error" });
        return;
      } else {
        if (this_.dataForm.orderSplitConditionEditList.length == 0) {
          let obj = {};
          let conditionValue = "";
          $.each(this_.dataFormMatching.conditionValue, function(index, val) {
            conditionValue += val + ",";
          });
          obj.variableName = this_.dataFormMatching.variableName;
          obj.operator = this_.dataFormMatching.operator;
          obj.conditionValue = conditionValue;
          this_.dataForm.orderSplitConditionEditList.push(obj);
          this.$message({ message: "操作成功", type: "success" });
          this.editDialogVisibleMatching = false;
          this.$refs["dataForm"].clearValidate("orderSplitConditionEditList");
        } else {
          let flag = true;
          $.each(this_.dataForm.orderSplitConditionEditList, function(
            index,
            val
          ) {
            if (val.variableName == this_.dataFormMatching.variableName) {
              this_.$message({ message: "存在相同的变量名", type: "error" });
              flag = false;
              return;
            }
          });

          if (flag) {
            let obj = {};
            let conditionValue = "";
            $.each(this_.dataFormMatching.conditionValue, function(index, val) {
              conditionValue += val + ",";
            });
            obj.variableName = this_.dataFormMatching.variableName;
            obj.operator = this_.dataFormMatching.operator;
            obj.conditionValue = conditionValue;
            this_.dataForm.orderSplitConditionEditList.push(obj);

            this.$message({ message: "操作成功", type: "success" });
            this.editDialogVisibleMatching = false;
          }
        }
      }
    },
    clearValidate1(formName) {
      this.$refs[formName].clearValidate();
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      this.filters = {
        ruleCode: "",
        ruleName: "",
        status: ""
      };
      this.findPage();
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      let temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    formateStatus(row, column, cellValue, index) {
      if (cellValue == "1") {
        return "启用";
      } else if (cellValue == "2") {
        return "停用";
      } else {
        return "未知";
      }
    },
    changeVariableName: function(data) {
      let this_ = this;
      if (data == "来源渠道") {
        this_.dataFormMatching.operator = "";
        this.dataFormMatching.conditionValue = [];
        this_.operatorOptions = [
          { key: 1, value: "=" },
          { key: 2, value: "!=" }
        ];
        this_.conditionValueOptions = [
          { key: "1", value: "BBC" },
          { key: "2", value: "天猫" },
          { key: "3", value: "京东" }
        ];
      } else if (data == "下单来源") {
        this_.dataFormMatching.operator = "";
        this.dataFormMatching.conditionValue = [];
        this_.operatorOptions = [{ key: 1, value: "=" }];
        this_.conditionValueOptions = [
          { key: "4", value: "前台下单" },
          { key: "5", value: "后台下单" }
        ];
      } else if (data == "商品供应商") {
        this_.dataFormMatching.operator = "";
        this.dataFormMatching.conditionValue = [];
        this_.operatorOptions = [{ key: 3, value: "is not null" }];
        this_.conditionValueOptions = [{ key: "6", value: "是" }];
      }
    }
  },
  mounted() {
    this.initColumns();
  }
};
</script>

<style lang='scss' scoped>
.pd20 {
  padding-bottom: 20px;
}
.tr {
  text-align: right;
}
</style>
